package com.simple.trade.service.india.impl;

import com.google.common.base.Preconditions;
import com.simple.common.entity.ReqContext;
import com.simple.common.entity.ResData;
import com.simple.common.entity.constant.Payment;
import com.simple.common.entity.dto.pay.india.IndiaBaseDto;
import com.simple.common.entity.dto.pay.india.V3PayDto;
import com.simple.common.entity.dto.pay.india.V3PayRspDto;
import com.simple.common.entity.po.sys.ChannelComp;
import com.simple.common.entity.po.sys.Product;
import com.simple.common.entity.po.sys.Trade;
import com.simple.common.entity.req.india.req.V3Req;
import com.simple.common.entity.req.india.res.V3Res;
import com.simple.common.entity.req.vm.pay.PayBase;
import com.simple.trade.service.india.V3PayService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;

/**
 * @description:
 * @author: Mr.Kang
 * @create: 2021-11-02 21:48
 **/
@Service
@Slf4j
public class V3PayServiceImpl extends V3PayBaseService<V3Res, V3PayRspDto> implements V3PayService {

    /**
     * 印度支付下单
     *
     * @param req
     * @return
     */
    @Override
    public ResData<V3Res> cashierPay(V3Req req) {
        return pay(req, trade -> {
            trade.setSyncUrl(req.getRedirectUrl());
        }, Payment.PAY_TYPE.INDIA_PAY);
    }

    @Override
    protected IndiaBaseDto getDto(Trade trade, ReqContext reqContext, PayBase payBase, ChannelComp channel, Product product) {
        V3PayDto v3PayDto = V3PayDto.generateDto(trade, reqContext, payBase.getExtraInfo(), channel, product);
        return v3PayDto;
    }

    @SneakyThrows
    @Override
    protected V3Res map(V3PayRspDto rsp) {
        Trade trade = rsp.getTrade();
        Preconditions.checkNotNull(trade, "支付失败渠道服务错误，交易不能为空");
        V3Res v3Res = new V3Res();
        v3Res.setSerialNo(trade.getId());
        v3Res.setOrderNo(trade.getMerchantOrderNo());
        v3Res.setCurrency(trade.getCurrency());
        v3Res.setAmount(trade.getAmount());
        v3Res.setPayStatus(trade.getStatus());
        v3Res.setRemark(trade.getOrderDesc());
        v3Res.setPayMsg(trade.getMsg());
        if (StringUtils.isNotBlank(rsp.getPayHtml())) {
            v3Res.setPayHtml(URLEncoder.encode(rsp.getPayHtml(), "UTF-8"));
        }
        else {
            v3Res.setPayHtml("");
        }
        if (StringUtils.isNotBlank(rsp.getPaymentUrl())) {
            v3Res.setPayUrl(URLEncoder.encode(rsp.getPaymentUrl(), "UTF-8"));
        }
        else {
            v3Res.setPayUrl("");
        }
        return v3Res;
    }
}
